import {
  checkLogin
} from './auth.js'

new Vue({
  el: '#app',
  data: {
    IS_LOGIN: null,
    searchKey: '',// 搜索的关键词,
    username: '',
    email: '',
    gender: 0,
    phone: '',
  },
  async created() {
    this.IS_LOGIN = await checkLogin()
    if (this.IS_LOGIN == null) {
      location.href = '/'
    }
    this.username = this.IS_LOGIN.username
  },
  mounted() {
    this.getUserData()
  },
  methods: {
    async updateUserInfo() {
      if (this.username == '' || this.email == '' || this.phone == '') {
        this.$message.error('请填写完整信息')
        return
      }
      if (!/0?(13|14|15|18|17|19)[0-9]{9}/.test(this.phone)) {
        this.$message.error('请填写正确的手机号')
        return
      }
      if (!/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(this.email)) {
        this.$message.error('请填写正确的邮箱')
        return
      }
      const res = await request.post('/user/updateUserInfo', {
        username: this.username,
        email: this.email,
        gender: this.gender,
        phone: this.phone,
      })
      if (res.code == 200) {
        this.$message.success('修改成功')
        this.getUserData();
      } else {
        this.$message.error('修改失败')
      }
    },
    async getUserData() {
      const res = await request.get('/user/getUserInfo')
      this.email = (res.data.email != null ? res.data.email : '')
      this.gender = res.data.gender
      this.phone = res.data.phone != null ? res.data.phone : ''
    },
    // 查找商品
    searchProduct() {
      console.log('查找商品:');
      location.href = `../web/search.html?searchKey=${this.searchKey}`
    },
    // 退出登录
    logout() {
      localStorage.removeItem('token')
      this.IS_LOGIN = null
      this.$message.success('退出成功')
      location.href = '/'
    },
  }
})